﻿using System;
using System.Runtime.InteropServices;

namespace GLDotNet
{
    public abstract class BufferBase<T> : GLObject
        where T : struct
    {
        protected abstract BufferTarget BufferTarget
        {
            get;
        }

        public BufferBase(GraphicsDevice graphicsDevice)
            : base(graphicsDevice)
        {              
        }

        protected uint GenerateBuffer()
        {
            uint buffer = 0;
            this.Context.GenBuffers(1, out buffer);
            return buffer;
        }
        
        protected override void DeleteObject()
        {
            uint buffer = this.Handle;
            this.Context.DeleteBuffers(1, ref buffer);
        }

        public void Bind()
        {
            this.GraphicsDevice.BindBuffer(this.BufferTarget, this.Handle);
        }

        public void SetData(T[] data, BufferUsage usage)
        {
            this.SetData(data, usage, (IntPtr)(Marshal.SizeOf(typeof(T)) * data.Length));
        }

        public void SetData(T[] data, BufferUsage usage, IntPtr size)
        {
            this.Bind();
            this.Context.BufferData<T>(this.BufferTarget, size, data, usage);
        }
    }
}
